<template>
  <div class="field-app-container">
    <div style="display:flex;align-items:center;">
      <Title v-if="showTitle" title="字段分类配置" />
      <span v-else style="flex:1;"/>
      <template v-if="!showMobilePage">
        <div v-if="hasRouteAuth('total:field:create')" class="field-app-header">
          <simple-button :style="{marginRight: '16px'}" name="新建字段" icon="el-icon-plus" @click="createField" />
          <simple-button :style="{marginRight: '16px'}" name="新建分类" icon="el-icon-plus" @click="createFieldType" />
          <simple-button name="批量导入字段" color-type="deep" @click="handelBatchAddField" />
        </div>
      </template>
      <MoreOpeator
        v-if="hasRouteAuth('total:field:create') && showMobilePage"
        :list="[
          {label: '新建字段', handelClick: createField},
          {label: '新建分类', handelClick: createFieldType},
          {label: '批量导入字段', handelClick: handelBatchAddField},
      ]"/>
    </div>
    <div class="list-box">
      <field-expand-table
        :table-data="tableData"
        :is-loadding="listLoading"
        @deleteFieldType="deleteFieldType"
        @editFieldType="editFieldType"
        @itemEdit="fieldItemEdit"
        @itemDelete="fieldItemDelete"
        @resetTableData="resetTableData" />
    </div>
    <add-field-dialog ref="addField" :field-info="editField" @closeDialog="closeDialog" @success="addSimFieldSuccess" />
    <addFieldModule ref="addBatchModule" :is-need-base-filed="false" import-api="/admin/field/importField" @onSuccess="onAddBatchSuccess" />
    <addFieldType ref="addFieldTypeRef" @callback="getData" />
  </div>
</template>
<script>
import Title from '@/components/Title';
import addFieldModule from '@/components/ReportManage/selectField/simpleAddField.vue';
import addFieldType from '@/components/ReportManage/selectField/addFieldType.vue';
import SimpleButton from '@/components/SimpleButton';
import FieldExpandTable from './module/fieldExpandTable';
import AddFieldDialog from '@/components/FieldManage/addFieldDialog';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import { getFieldList, deleteField, batchField, deleteFieldType } from '@/api/fieldManage';
import store from '@/store';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';

export default {
  name: 'MediumOrder',
  components: {
    SimpleButton,
    FieldExpandTable,
    AddFieldDialog,
    addFieldModule,
    Title,
    addFieldType,
    MoreOpeator
  },
  props: {
    showTitle: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableData: [],
      listLoading: true,
      editField: null
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  created() {
    this.getData();
  },
  methods: {
    hasRouteAuth,
    // 关闭窗口
    closeDialog() {
      this.editField = null;
    },
    createField() {
      this.editField = null;
      this.$refs.addField.dialogShow();
    },
    async getData() {
      this.$store.dispatch('GetFieldCategorys');
      try {
        const params = {
          name: '',
          use: 1
        };
        this.listLoading = true;
        const res = await getFieldList(params);
        this.listLoading = false;
        if (res.data) {
          this.tableData = res.data;
          store.commit('SET_FIELDLIST', res.data);
        }
      } catch (error) {
        this.listLoading = false;
        console.error(error);
      }
    },
    fieldItemEdit(data) {
      this.editField = data.info;
      this.$refs.addField.dialogShow();
    },
    fieldItemDelete(data) {
      const param = {
        fieldId: data.info.id
      };
      deleteField(param).then(res => {
        if (res.code === 200) {
          this.$message({ type: 'success', message: '删除成功' });
          this.tableData[data.parentIndex].fieldInfo.splice(data.childrenIndex, 1);
        } else {
          const message = res.message ? res.message : '删除失败';
          this.$message({
            type: 'error',
            message: message
          });
        }
      });
    },
    handelBatchAddField() {
      this.$refs.addBatchModule.dialogVisible = true;
    },
    onAddBatchSuccess(data) {
      const fieldList = [];
      data.params.forEach((i) => {
        fieldList.push(i.label);
      });
      const param = {
        fieldList: [
          {
            categoryId: data.categoryId,
            fieldListItem: fieldList
          }
        ]
      };
      batchField(param).then(res => {
        if (res.code === 200) {
          if (res.data) {
            this.$refs.addBatchModule.handleRepeatField(res.data);
            this.$message({ type: 'info', message: '已自动过滤掉重复数据，请再次提交' });
          } else {
            this.$refs.addBatchModule.dialogVisible = false;
            this.$message({ type: 'success', message: '添加成功' });
            this.getData();
          }
        } else {
          const message = res.message ? res.message : '创建失败';
          this.$message({
            type: 'error',
            message: message
          });
        }
      });
    },
    addSimFieldSuccess() {
      this.getData();
    },
    resetTableData(list) {
      this.tableData = list;
    },
    createFieldType() {
      this.$refs.addFieldTypeRef.openDialog();
    },
    editFieldType(item) {
      this.$refs.addFieldTypeRef.openDialog({ id: item.id, name: item.name });
    },
    deleteFieldType(item) {
      this.$confirm('是否确定删除？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        deleteFieldType({ id: item.id }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getData(true);
          } else {
            this.$message.error(res.message);
          }
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.field-app-container {
  margin: 20px;
  // border:1px solid #eee;
  // box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
  // border-radius:12px;
  background-color: #fff;
  padding: 18px 24px 24px 24px;
  min-height: calc(100vh - 96px);
  .field-app-header {
    display: flex;
    justify-content: flex-end;
  }
  .list-box {
    margin-top: 13px;
  }
}
</style>
